<template>
    <view class="contentWrap">
        <view v-if="current === '0'">
            <view>
                <u-text
                    prefixIcon="account"
                    iconStyle="font-size: 26px;color:#588BF3"
                    text="拜访客户"
                    bold
                    size="32rpx"
                    color="#333333"
                />
            </view>
            <view class="dateWrap flex_wrap" @click="openBody">
                <u-text
                    :text="name ? name : '请选择客户'"
                    bold
                    size="28rpx"
                    :color="name ? '#666666' : '#c0c4cc'"
                />
                <u-icon
                    name="arrow-right"
                    color="#999999"
                    size="20"
                    align="right"
                ></u-icon>
            </view>
        </view>
        <view v-if="current === '1'">
            <view>
                <u-text
                    prefixIcon="bookmark"
                    iconStyle="font-size: 26px;color:#588BF3"
                    text="摘要标题"
                    bold
                    size="32rpx"
                    color="#333333"
                />
            </view>
            <view class="dateWrap flex_wrap">
                <u--input
                    placeholder="请输入标题内容"
                    border="none"
                    clearable
                    v-model="noteTitle"
                ></u--input>
            </view>
        </view>
        <u-gap height="10" bgColor="#fff"></u-gap>
        <view>
            <view>
                <u-text
                    prefixIcon="calendar"
                    iconStyle="font-size: 26px;color:#588BF3"
                    :text="
                        current === '0'
                            ? '拜访时间'
                            : current === '2'
                            ? '保单时间'
                            : '摘要时间'
                    "
                    bold
                    size="32rpx"
                    color="#333333"
                />
            </view>
            <view class="dateWrap flex_wrap" @click="openDate">
                <u-text
                    :text="createTime ? createTime : '请选择时间'"
                    bold
                    size="28rpx"
                    :color="createTime ? '#666666' : '#c0c4cc'"
                />
                <u-icon
                    name="arrow-right"
                    color="#999999"
                    size="20"
                    align="right"
                ></u-icon>
            </view>
        </view>
        <u-gap height="10" bgColor="#fff"></u-gap>
        <view>
            <view>
                <u-text
                    prefixIcon="file-text"
                    iconStyle="font-size: 26px;color:#588BF3"
                    :text="
                        current === '0'
                            ? '拜访内容'
                            : current === '2'
                            ? '保单备注'
                            : '摘要内容'
                    "
                    bold
                    size="32rpx"
                    color="#333333"
                />
            </view>
            <view style="margin-left: 36rpx">
                <u-textarea
                    v-model="info"
                    ref="textarea"
                    count
                    :formatter="formatter"
                    :confirmType="null"
                    maxlength="500"
                    placeholder="请编辑内容"
                    height="500rpx"
                    :customStyle="{
                        backgroundColor: '#F1F1F1',
                        color: '#666',
                        width: '100%',
                        padding: '20rpx',
                        paddingBottom: '40rpx',
                        boxSizing: 'border-box',
                        fontSize: '26rpx',
                        margin: '10rpx 0',
                    }"
                ></u-textarea>
            </view>
        </view>
        <u-gap height="10" bgColor="#fff"></u-gap>
        <view v-if="current !== '2'">
            <view class="flex_wrap">
                <u-text
                    prefixIcon="photo"
                    iconStyle="font-size: 26px;color:#588BF3"
                    text="图片/视频"
                    bold
                    size="32rpx"
                    color="#333333"
                />
                <u-text
                    color="#777"
                    size="32rpx"
                    align="right"
                    :text="fileList1.length + `/8`"
                />
            </view>
            <view style="margin: 20rpx 36rpx">
                <u-upload
                    :maxCount="8"
                    :fileList="fileList1"
                    @delete="deleteVideo"
                    @afterRead="afterRead1"
                    :accept="video || image"
                    compressed
                    maxDuration="30"
                ></u-upload>
            </view>
        </view>
        <view v-if="current === '2'">
            <view class="flex_wrap">
                <u-text
                    prefixIcon="photo"
                    iconStyle="font-size: 26px;color:#588BF3"
                    text="保单图片"
                    bold
                    size="32rpx"
                    color="#333333"
                />
                <u-text
                    color="#777"
                    size="32rpx"
                    align="right"
                    :text="fileList1.length + `/8`"
                />
            </view>
            <view style="margin: 20rpx 36rpx">
                <u-upload
                    :maxCount="8"
                    :fileList="fileList1"
                    @delete="deleteVideo"
                    @afterRead="afterRead1"
                ></u-upload>
            </view>
        </view>
        <u-gap height="20" bgColor="#fff"></u-gap>
        <view>
            <u-button
                type="primary"
                shape="circle"
                :text="type !== '编辑' ? '确定' : '修改完成'"
                color="#588BF3"
                @click="okbook"
                :customStyle="okbookBtn"
            ></u-button>
        </view>

        <view class="">
            <u-action-sheet
                :actions="list"
                :closeOnClickOverlay="true"
                @select="selectClick"
                :show="bodyShow"
                cancelText="取消"
                @close="bodyShow = false"
            ></u-action-sheet>
        </view>

        <view>
            <u-datetime-picker
                :show="showDate"
                v-model="value1"
                mode="date"
                autoHeight
                @cancel="timePicerCancel"
                @confirm="timePickerConfirm"
                closeOnClickOverlay
            ></u-datetime-picker>
        </view>

        <view>
            <u-popup
                :round="20"
                :show="selectBodyShow"
                @close="closeselectBody"
                bgColor="#F6F6F6"
                :closeOnClickOverlay="false"
            >
                <view>
                    <view class="search">
                        <u-search
                            placeholder="请输入关键字"
                            v-model="keyword"
                            bgColor="#E1E1E1"
                            color="#333"
                            placeholderColor="#999999"
                            clearabled
                            height="64rpx"
                            @custom="keywordSearch"
                            :actionStyle="actionStyle"
                        />
                    </view>
                    <view class="scrollViews">
                        <view>
                            <u-radio-group
                                v-model="radiovalue1"
                                placement="column"
                                @change="groupChange"
                            >
                                <view
                                    class="item flex_wrap flex_column"
                                    v-for="(item, index) in dataList"
                                    :key="index"
                                >
                                    <view>
                                        <view
                                            class="topMessage flex_wrap row_between"
                                        >
                                            <view class="flex_wrap row_middle">
                                                <u-image
                                                    :src="
                                                        item.avatar ||
                                                        MissingAvatar
                                                    "
                                                    width="100rpx"
                                                    height="100rpx"
                                                    bgColor="#eee"
                                                    shape="circle"
                                                />
                                                <view
                                                    class="flex_wrap flex_column"
                                                >
                                                    <view
                                                        style="
                                                            margin-left: 20rpx;
                                                        "
                                                    >
                                                        <view class="flex_wrap">
                                                            <u-text
                                                                :text="
                                                                    item.latestSignInNotes ||
                                                                    item.nickName ||
                                                                    '微信用户'
                                                                "
                                                                color="#333"
                                                                bold
                                                                size="40rpx"
                                                            />
                                                            <view
                                                                style="
                                                                    position: absolute;
                                                                    right: 116rpx;
                                                                    top: 62rpx;
                                                                "
                                                            >
                                                                <u-rate
                                                                    :count="5"
                                                                    :value="
                                                                        item.customerStar
                                                                    "
                                                                    activeColor="#FFAA00"
                                                                    readonly
                                                                ></u-rate>
                                                            </view>
                                                        </view>
                                                        <u-gap height="10rpx" />
                                                        <u-text
                                                            color="#666"
                                                            :text="
                                                                item.customerPhone ||
                                                                '--'
                                                            "
                                                        />
                                                    </view>
                                                </view>
                                            </view>
                                            <view
                                                style="
                                                    margin-top: 20rpx;
                                                    text-align: right;
                                                "
                                            >
                                                <u-radio
                                                    activeColor="#588BF3"
                                                    :key="index"
                                                    :name="item.customerId"
                                                ></u-radio>
                                            </view>
                                        </view>
                                    </view>
                                </view>
                            </u-radio-group>
                        </view>
                    </view>
                    <view class="selsetBtn">
                        <u-button
                            type="primary"
                            shape="circle"
                            text="确定"
                            color="#588BF3"
                            @click="okselect"
                        ></u-button>
                    </view>
                </view>
            </u-popup>
        </view>
    </view>
</template>

<script>
import { baseUrl } from "@/config/tendIdConfig";
import { pageCustomerManageBySalesmanId } from "@/api/userManageSalesman.js";
import { note_service, edit } from "@/api/mybookSalesman.js";
export default {
    data() {
        return {
            value1: Number(new Date()),
            createTime: "",
            info: "",
            type: "",
            editData: "",
            showDate: false,
            bodyShow: false,
            selectBodyShow: false,
            okbookBtn: {
                width: "404rpx",
                height: "88rpx",
            },
            list: [
                {
                    name: "无",
                },
                {
                    name: "选择客户",
                },
            ],

            name: "",
            nameId: "",
            dataList: [],
            couponRadiovalue: "",
            radiovalue1: "",
            keyword: "",
            current: "0",
            type: "",
            details: {},
            title: "",
            noteTitle: "",
            fileList1: [],
            pictureUrl: {},
            backType: "",
        };
    },
    onReady() {
        this.$refs.textarea.setFormatter(this.formatter);
    },
    onLoad(options) {
        this.type = options.type;
        this.current = options.current;
        this.backType = options.backType;
        this.nameId = options.customerId || "";
        console.log(this.nameId, "this.nameId>>>");
        uni.setNavigationBarTitle({
            title: this.type == "编辑" ? "编辑内容" : "新增内容",
        });
        if (this.type == "编辑") {
            this.details = options?.data && JSON.parse(options?.data);
            this.createTime = uni.$u.timeFormat(
                this.details.createTime,
                "yyyy-mm-dd"
            );
            this.value1 = this.details.createTime;
            this.info = this.details.info;
            this.nameId = this.details.customerId;
            this.name = this.details.customerName;
            this.fileListNew =
                this.details.pictureUrl && this.details.pictureUrl.split(",");
            this.fileListNew &&
                this.fileListNew.forEach((item) => {
                    var obj = {};
                    var str1 = "url";
                    obj[str1] = item;
                    this.fileList1.push(obj);
                });
            this.noteTitle = this.details.title;
            if (this.nameId) {
                this.name = this.details.customerName || "微信用户";
            }
        }
        this.$store.getters?.authority === "salesman" && this.queryList();
    },
    methods: {
        async afterRead1(event) {
            // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
            let lists = [].concat(event.file);
            let fileListLen = this.fileList1.length;
            lists.map((item) => {
                this.fileList1.push({
                    ...item,
                    status: "uploading",
                    message: "上传中",
                });
            });
            for (let i = 0; i < lists.length; i++) {
                const result = await this.uploadFilePromise(lists[i].url);
                let item = this.fileList1[fileListLen];
                this.fileList1.splice(
                    fileListLen,
                    1,
                    Object.assign(item, {
                        status: "success",
                        message: "",
                        uploadResult: result,
                        url: result,
                    })
                );
                fileListLen++;
            }
        },
        deleteVideo(event) {
            this.fileList1.splice(event.index, 1);
        },
        async uploadFilePromise(url) {
            const that = this;
            return new Promise((resolve, reject) => {
                const token = uni.getStorageSync("access_token");
                let a = uni.uploadFile({
                    url: `${baseUrl}/${this.$store.getters?.authority}/fileOss/uploadFileImg`,
                    filePath: url,
                    header: {
                        "Content-Type": "multipart/form-data",
                        Authorization: `Bearer ${token}` || "",
                    },
                    name: "file",
                    success: (res) => {
                        const result = JSON.parse(res.data);
                        if (result.code === 200) {
                            uni.showToast({
                                title: "上传成功",
                                icon: "success",
                            });
                            setTimeout(() => {
                                resolve(result.data);
                            }, 1000);
                        } else {
                            uni.showToast({
                                title: "上传失败",
                                icon: "fail",
                            });
                            setTimeout(() => {
                                reject(result.msg);
                            }, 1000);
                        }
                    },
                });
            });
        },
        groupChange(n) {
            this.nameId = n;
            this.changeDetail = this.dataList.filter(
                (v) => v.customerId === n
            )[0];
            this.name =
                this.changeDetail.nickName ||
                this.changeDetail.latestSignInNotes ||
                "微信用户";
        },
        okselect() {
            this.selectBodyShow = false;
        },
        keywordSearch() {
            this.queryList();
        },
        async queryList() {
            const params = {
                pageNum: 1,
                pageSize: 16,
                orderType: "2", //正序 1倒序 2
                sortField: 2, //时间排序 1 星级排序 2
            };
            if (this.keyword) params.query = this.keyword;
            const result = await pageCustomerManageBySalesmanId(params);
            this.dataList = result.data.rows;
            this.total = result.data.total;
        },
        closeselectBody() {
            this.selectBodyShow = false;
        },
        selectClick(index) {
            this.selectName = index.name;
            if (this.selectName == "无") {
                this.name = this.selectName;
            } else {
                this.selectBodyShow = true;
            }
            this.bodyShow = false;
        },
        openBody() {
            this.bodyShow = true;
        },
        formatter(value) {
            if (value.length > 500) return value.slice(0, 500);
            return value;
        },
        deleteFun(item) {
            this.editData = item;
            this.modalShow = true;
        },
        edit(item) {
            this.type = "编辑";
            this.editData = item;
            this.show = true;
            this.createTime = uni.$u.timeFormat(item.createTime, "yyyy-mm-dd");
            this.value1 = item.createTime;
            this.info = item.info;
        },
        okbook() {
            if (!this.info.trim().length || !this.createTime)
                return uni.$u.toast("请选择时间和填写内容！");
            const params = {
                info: this.info.trim(),
                createTime: this.createTime + " 00:00:00",
                notepadType: this.current,
                customerId: this.nameId,
                title: this.noteTitle,
                pictureUrl: this.fileList1.map((v) => v.url).join(","),
            };
            if (this.type === "添加") {
                note_service(params).then((res) => {
                    this.close();
                    uni.navigateBack({
                        delta: 1,
                    });
                });

                return;
            } else {
                //  修改
                params.id = this.details.id;
                edit(params).then((res) => {
                    this.close();
                    this.backType == "详情"
                        ? uni.reLaunch({
                              url: "/pages_balance/laptop/index/index",
                          })
                        : uni.navigateBack({
                              delta: 1,
                          });
                });
            }
        },
        openDate() {
            this.showDate = true;
            this.value1 = this.createTime || Number(new Date());
        },
        open() {},
        close() {
            this.show = false;
            this.show = false;
            this.createTime = "";
            this.info = "";
            // this.value1 = Number(new Date());
        },
        timePickerConfirm(e) {
            const timeFormat = uni.$u.timeFormat;
            this.createTime = timeFormat(e.value, "yyyy-mm-dd");
            this.value1 = e.value;
            this.timePicerCancel();
        },
        timePicerCancel() {
            this.showDate = false;
        },
    },
};
</script>

<style lang="scss" scoped>
.search {
    padding: 32rpx 28rpx;
}

.contentWrap {
    background: #ffffff;
    border-radius: 16rpx 16rpx 0rpx 0rpx;
    margin: 40rpx 28rpx 0;
    box-sizing: border-box;
    overflow: hidden;
    padding: 34rpx 24rpx;
}

.dateWrap {
    // width: 100%;
    height: 80rpx;
    box-sizing: border-box;
    background: #f1f1f1;
    border-radius: 8rpx 8rpx 8rpx 8rpx;
    opacity: 1;
    line-height: 80rpx;
    padding-left: 40rpx;
    padding-right: 20rpx;
    margin: 20rpx 0 0 36rpx;
}

.selsetBtn {
    padding: 60rpx 60rpx 30rpx;
}

.scrollViews {
    height: 70vh;
    overflow-y: scroll;
    width: 100%;
    padding: 30upx 28upx 0 28upx;
    box-sizing: border-box;
    background: #f7f7f7;
    margin-top: 10rpx;

    .item {
        width: 100%;
        height: auto;
        border-radius: 20rpx 20rpx 20rpx 20rpx;
        margin-bottom: 40upx;
        background-color: #fff;

        .topMessage {
            padding: 30upx 20rpx;
            // border-bottom: 1px solid #dddadf;
            text-align: center;
            position: relative;
        }

        .statusBg {
            width: 121rpx;
            height: 40rpx;
            font-size: 24rpx;
            font-weight: 400;
            color: #ffffff;
            line-height: 40rpx;
            text-align: center;
            background-size: contain;
        }

        .bottomMessage {
            padding: 20upx;
            box-sizing: border-box;
            background-color: rgba(245, 246, 250, 0.6);
        }

        .timeBox {
            margin-left: 100rpx;
        }
    }
}
</style>
